package com.cloudcc.mobile.bull;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.bull.bean.ShopBean;
import com.cloudcc.mobile.bull.utils.LocalUtil;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.log.Log;
import com.mypage.utils.UtilsShowDialog;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopAddressActivity extends Activity {

    String id;
    UtilsShowDialog showDialog;
    @Bind(R.id.back)
    ImageButton back;
    @Bind(R.id.save)
    Button save;
    @Bind(R.id.re_title)
    RelativeLayout reTitle;
    @Bind(R.id.ll_bottom)
    TextView llBottom;
    @Bind(R.id.mapView)
    MapView mapView;
    @Bind(R.id.tv_shop_name)
    TextView tvShopName;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tv_zb)
    TextView tvZb;
    BaiduMap baiduMap;
    String address,jw;
    String proId,cityId,quId,proName,cityName,quName,jxsId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_address);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        id = getIntent().getStringExtra("id");
        showDialog = new UtilsShowDialog(this);
        getAddress();
        mapShow();
    }

    private void getAddress() {
        String expressions = "id='" + id + "'";
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "cquery");//普通插入服务
        params.addBodyParameter("objectApiName", "mendian");
        params.addBodyParameter("expressions", expressions);
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        showDialog.onDismissLoadingDialog();
                        //  Toast.makeText(ShopAddressActivity.this, "新建门店出错", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        Log.d("---res", arg0.result);
                        try {
                            JSONObject myJsonObject = new JSONObject(arg0.result);
                            String result = myJsonObject.getString("result");
                            String returnInfo = myJsonObject.getString("returnInfo");
                            String data = myJsonObject.getString("data");
                            if (result.equals("true")) {
                                Gson gson = new Gson();
                                List<ShopBean> appList = gson.fromJson(data, new
                                        TypeToken<List<ShopBean>>() {}.getType());
                                if(appList.size()>0){
                                    String zb=appList.get(0).getDzzb();
                                    tvShopName.setText(appList.get(0).getName());
                                    if(zb==null||"".equals(zb)){

                                    }else {
                                        Toast.makeText(ShopAddressActivity.this, "已有位置，无需再次上传", Toast.LENGTH_SHORT).show();
                                        finish();
                                    }
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }
                        showDialog.onDismissLoadingDialog();
                    }
                });

    }

    @OnClick({R.id.back, R.id.save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.save:
                save();
                break;
        }
    }
    private void mapShow() {
        baiduMap=mapView.getMap();
        baiduMap.setMyLocationEnabled(true);
        LocalUtil localUtil=new LocalUtil();
        localUtil.getLoc(this, new LocalUtil.Res() {
            @Override
            public void getLoc(BDLocation location) {
                MyLocationData.Builder builder = new MyLocationData.Builder();
                builder.latitude(location.getLatitude());
                builder.longitude(location.getLongitude());
                MyLocationData data = builder.build();
                baiduMap.setMyLocationData(data);
                LatLng latLng =new LatLng(location.getLatitude(),location.getLongitude());
                MapStatusUpdate msu= MapStatusUpdateFactory.newLatLng(latLng);
                baiduMap.animateMapStatus(msu);
                jw=(location.getLongitude()+","+location.getLatitude());
                address=location.getProvince()+location.getCity()+ location.getDistrict()+location.getStreet()+location.getLocationDescribe();
                proName=location.getProvince();
                cityName=location.getCity();
                quName=location.getDistrict();
                tvAddress.setText(location.getProvince()+location.getCity()+ location.getDistrict()+location.getStreet()+location.getLocationDescribe());
                tvZb.setText(jw);
            }
        });


    }

   private void save(){
       Map<String,String> map=new HashMap<>();
          if("4.9E-324,4.9E-324".equals(jw)){
              Toast.makeText(this, "定位信息出错，请重新定位", Toast.LENGTH_SHORT).show();
              return;
          }
       map.put("dzzb",jw);
       map.put("mddz",address);
       map.put("id",id);
       map.put("sf",proName);
       map.put("cs",cityName);
       map.put("xq",quName);
       Gson gson=new Gson();
       String data="["+gson.toJson(map)+"]";
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "update");//普通插入服务
        params.addBodyParameter("objectApiName", "mendian");
        params.addBodyParameter("data", data);
        Log.d("---data",data);
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        showDialog.onDismissLoadingDialog();
                        Toast.makeText(ShopAddressActivity.this, "上传位置出错", Toast.LENGTH_SHORT).show();
                        Log.d("---resError-------------------------", arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        Log.d("---res", arg0.result);
                        try {
                            JSONObject myJsonObject = new JSONObject(arg0.result);
                            String result=myJsonObject.getString("result");
                            String returnInfo=myJsonObject.getString("returnInfo");
                            if(result.equals("true")){
                                 Toast.makeText(ShopAddressActivity.this, "上传位置成功!", Toast.LENGTH_SHORT).show();
                                finish();

                            }else {
                                if(returnInfo.indexOf("：") != -1){
                                    returnInfo=returnInfo.substring(returnInfo.indexOf("：")+1,returnInfo.length());
                                }
                                Toast.makeText(ShopAddressActivity.this, returnInfo, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(ShopAddressActivity.this, "上传位置出错", Toast.LENGTH_SHORT).show();
                        }
                        showDialog.onDismissLoadingDialog();
                        finish();
                    }
                });



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mapView.onPause();
    }
}
